package com.cn.crmsystem.service.systemService.impl;

import com.cn.crmsystem.mapper.systemMapper.LoginMapper;
import com.cn.crmsystem.mapper.systemMapper.UserMapper;
import com.cn.crmsystem.pojo.ResultJson;
import com.cn.crmsystem.pojo.User;
import com.cn.crmsystem.service.systemService.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public ResultJson selectUser(Map map) {
        List<User> list = userMapper.selectAllUser(map);
        ResultJson resultJson = new ResultJson();
        if (list != null && list.size() > 0){
            resultJson.getSuccess("查询成功", list);
        }else{
            resultJson.getFail("查询失败");
        }
        return resultJson;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson addUser(String username, String password) {
        //新增User 然后添加登录信息
        User user = new User();
        int rows = userMapper.addUser(user);
        System.out.println(rows + "rows---------id = " + user.getId());
        if (rows > 0){
            //添加login
            rows = loginMapper.regLogin(username, password, user.getId());
        }
        if (rows > 0){
            return new ResultJson().getSuccess("注册成功");
        }else {
            return new ResultJson().getFail("注册失败");
        }
    }

    @Override
    public ResultJson deleteUser(Integer id) {
        int rows = userMapper.deleteUser(id);
        if (rows > 0){
            return new ResultJson<>().getSuccess("删除成功");
        }
        return new ResultJson().getFail("删除失败");
    }

    @Override
    public ResultJson updateUser(Map map) {
        int rows = userMapper.updateUser(map);
        if (rows > 0){
            return new ResultJson().getSuccess("修改成功");
        }
        return new ResultJson().getFail("修改失败");
    }

    @Override
    public ResultJson deleteManyUser(Integer[] ids) {
        int result=0;
        for(int i=0;i<ids.length;i++){
            result=userMapper.deleteUser(ids[i]);
        }
        if(result>0){
            return new ResultJson<>().getSuccess("删除成功");
        }else{
            return new ResultJson<>().getSuccess("删除失败");
        }
    }
}
